再來修改 ProductList.vue 與 ProductInfo.vue,由於 product-service 回傳的內容已經更改為 Observable 物件,因應變動 created 的資料處理邏輯
在 created 訂閱 productService.get() 回傳的 observable 物件,並處理 next() 觸發事件
this.$subscribeTo(productService.get(), (res) => {
this.products = res.response;
});
當使用 VueRx 的 $subscribeTo 時,component 在銷毀時會幫我們處理 Observable 的 unsubscribe,因此不需
要另外在 destroy 時 unsubcribe
完整程式碼
<script>
import productService from '@/services/product-service';
export default {
name: 'ProductList',
data() {
return {
products: [],
};
},
created() {
this.$subscribeTo(productService.get(), (res) => {
this.products = res.response;
});
},
methods: {
onProductClick(product) {
this.$router.push({ name: 'productInfo', params: { id: product.id } });
},
},
};
</script>
ProductInfo.vue
<script>
import productService from '@/services/product-service';
export default {
name: 'ProductInfo',
data() {
return {
product: {},
quantity: 0,
};
},
created() {
this.$subscribeTo(productService.get(this.$route.params.id), (res) => {
this.product = res.response;
});
},
computed: {
amount() {
return this.product.price * this.quantity;
},
},
methods: {
onBackClick() {
this.$router.back();
},
},
};
</script>